#include "z_terminal.h"
#include <stdio.h>
#include <unistd.h>
#include <termios.h>
#include <fcntl.h>

struct termios oterm;

int set_term_mode(int fd)
{
	struct termios term;
	if (tcgetattr(fd, &term) == -1 || tcgetattr(fd, &oterm) == -1) {
		printf("Cannot get the attribution of the terminal");
		return -1;
	}

	term.c_lflag &= ~(ECHO | ICANON);

	if (tcsetattr(fd, TCSAFLUSH, &term) == -1) {
		printf("Cannot set the attribution of the terminal");
		return -1;
	}

	/* set stdin nonblock */
	int flag = fcntl(STDIN_FILENO, F_GETFL);
	flag |= O_NONBLOCK;
	if (fcntl(STDIN_FILENO, F_SETFL, flag) == -1) {
		printf("Cannot set the O_NONBLOCK of the STDIN_FILENO");
		return -1;
	}
	return 0;
}

int resume_term_mode(int fd)
{
	if (tcsetattr(fd, TCSAFLUSH, &oterm) == -1) {
		printf("Cannot resume the attribution of the terminal");
		return -1;
	}
	return 0;
}

void set_key()  
{  
	struct termios new_oterm;  
	tcgetattr(0,&oterm);  
	new_oterm=oterm;  
	new_oterm.c_lflag&=~(ICANON|ECHO|ISIG);  
	new_oterm.c_cc[VTIME]=0;  
	new_oterm.c_cc[VMIN]=1;  
	tcsetattr(0,TCSANOW,&new_oterm);  
	return;  
}  
void reset_key()  
{  
	tcsetattr(0,TCSANOW,&oterm);  
	return;  
}
